package com.pphh.demo.gateway;

import com.pphh.demo.gateway.filter.PreGatewayFilterFactory;
import com.pphh.demo.gateway.filter.RequestTimeFilter;
import com.pphh.demo.gateway.filter.TokenFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 2019/4/16
 */
@Configuration
public class GatewayAutoConfiguration {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route", r -> r.path("/get")
                        .uri("http://httpbin.org")
                )
                .route("test_route", r -> r.path("/test/**")
                        .filters(f -> f.filter((exchange, chain) -> {
                            ServerHttpRequest req = exchange.getRequest();
                            addOriginalRequestUrl(exchange, req.getURI());
                            String path = req.getURI().getRawPath();
                            String newPath = path.replaceAll("/test/(?<segment>.*)", "/${segment}");
                            ServerHttpRequest request = req.mutate()
                                    .path(newPath)
                                    .build();
                            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
                            return chain.filter(exchange.mutate().request(request).build());
                        }))
                        .uri("http://httpbin.org")
                )
                .route("x_route", r -> r.path("/x/**")
                        .filters(f -> f.rewritePath("/x/(?<segment>.*)", "/api/${segment}"))
                        .uri("http://x.pphh.com:8080")
                )
                .route("y_route", r -> r.path("/y/**")
                        .filters(f -> f.rewritePath("/y/(?<segment>.*)", "/api/${segment}")
                                .filter(new RequestTimeFilter())
                                .addResponseHeader("X-Response-Default-Foo", "Default-Bar")
                        )
                        .uri("http://y.pphh.com:8080")
                        .order(0)
                        .id("customer_filter_router")
                )
                .build();
    }

    @Bean
    public PreGatewayFilterFactory addRequestHeaderGatewayFilterFactory() {
        return new PreGatewayFilterFactory();
    }

    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

}
